/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package presentation.view;

import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import presentation.controller.ControlPanelAddContact;
import presentation.controller.ControlPanelMyAccount;
import vo.ContactVO;

/**
 *
 * @author Joanna 8a
 */
public class PanelAddContact extends javax.swing.JPanel {

    /**
     * Creates new form PanelAddContact
     */
    public PanelAddContact(AuxiliarFrame parent) {
        this.parent = parent;
        initComponents();
        this.parent = parent;
        parent.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/presentation/view/images/Thumb Up.png")).getImage());
        errorNuevoTelefono = false;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelNames = new javax.swing.JLabel();
        jTextFieldNames = new javax.swing.JTextField();
        jLabelLastName = new javax.swing.JLabel();
        jTextFieldLastName = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListPhones = new javax.swing.JList();
        jLabelPhones = new javax.swing.JLabel();
        jLabelEmail = new javax.swing.JLabel();
        jTextFieldEmail = new javax.swing.JTextField();
        jButtonSave = new javax.swing.JButton();
        jButtonBack = new javax.swing.JButton();
        jButtonAddPhone = new javax.swing.JButton();
        jButtonModifyPhone = new javax.swing.JButton();
        jButtonDeletePhone = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Agregar Contacto", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI Light", 1, 14), java.awt.Color.black)); // NOI18N

        jLabelNames.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jLabelNames.setText("Nombres");

        jTextFieldNames.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N

        jLabelLastName.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jLabelLastName.setText("Apellidos");

        jTextFieldLastName.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N

        jListPhones.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jListPhones.setModel(new DefaultListModel<Long>());
        jListPhones.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jListPhones);

        jLabelPhones.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jLabelPhones.setText("Teléfonos");

        jLabelEmail.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jLabelEmail.setText("E-mail");

        jTextFieldEmail.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jTextFieldEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldEmailActionPerformed(evt);
            }
        });

        jButtonSave.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jButtonSave.setText("Guardar");
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });

        jButtonBack.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jButtonBack.setText("Volver");
        jButtonBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBackActionPerformed(evt);
            }
        });

        jButtonAddPhone.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jButtonAddPhone.setText("Agregar Telefono");
        jButtonAddPhone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddPhoneActionPerformed(evt);
            }
        });

        jButtonModifyPhone.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jButtonModifyPhone.setText("Modificar Telefono");
        jButtonModifyPhone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModifyPhoneActionPerformed(evt);
            }
        });

        jButtonDeletePhone.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jButtonDeletePhone.setText("Eliminar Telefono");
        jButtonDeletePhone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeletePhoneActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelEmail)
                        .addGap(20, 20, 20)
                        .addComponent(jTextFieldEmail))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addComponent(jButtonSave)
                        .addGap(70, 70, 70)
                        .addComponent(jButtonBack))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabelNames)
                            .addComponent(jLabelLastName))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextFieldNames, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
                            .addComponent(jTextFieldLastName, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButtonModifyPhone, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButtonDeletePhone, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButtonAddPhone, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(20, 20, 20)
                        .addComponent(jLabelPhones)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelNames)
                    .addComponent(jTextFieldNames, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelLastName)
                    .addComponent(jTextFieldLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelPhones)
                            .addComponent(jButtonAddPhone))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonModifyPhone)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonDeletePhone))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelEmail)
                    .addComponent(jTextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonSave)
                    .addComponent(jButtonBack))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTextFieldEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldEmailActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldEmailActionPerformed

    private void jButtonBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBackActionPerformed
        parent.dispose();
    }//GEN-LAST:event_jButtonBackActionPerformed

    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
        ContactVO contacto = new ContactVO();
        if ((!jTextFieldNames.getText().equals("") || !jTextFieldLastName.getText().equals("")) && (!jTextFieldEmail.getText().equals("") || jListPhones.getModel().getSize() != 0)) {
            contacto.setLastName(jTextFieldLastName.getText());
            contacto.setName(jTextFieldNames.getText());
            DefaultListModel<Long> model = (DefaultListModel<Long>) jListPhones.getModel();
            List<Double> list = new ArrayList<>();

            for (int i = 0; i < model.size(); i++) {
                list.add((double) model.getElementAt(i));
            }

            contacto.setPhones(list);
            contacto.setEmail(jTextFieldEmail.getText());
            contacto.setStudentId(new ControlPanelMyAccount().findByIp().getUsername());

            String result = new ControlPanelAddContact().addContact(contacto);

            if (result.equals("OK")) {
                JOptionPane.showMessageDialog(parent, "El contacto ha sido agregado satisfactoriamente", result, JOptionPane.INFORMATION_MESSAGE,
                        new ImageIcon(getClass().getResource("/presentation/view/images/Ok.png")));
                parent.dispose();
            } else {
                JOptionPane.showMessageDialog(parent, "Ha ocurrido un error y el contacto no pudo ser agregado", "Ooops!!!", JOptionPane.ERROR_MESSAGE,
                        new ImageIcon(getClass().getResource("/presentation/view/images/Exclamation.png")));
            }
        
        }else {
            if((jTextFieldNames.getText().equals("") && jTextFieldLastName.getText().equals(""))){
                JOptionPane.showMessageDialog(parent, "Se debe proporcionar un nombre o apellido del contacto", "Error!!!", JOptionPane.ERROR_MESSAGE);
            }
            else{
                JOptionPane.showMessageDialog(parent, "Se debe proporcionar un numero telefonico o un e-mail de contacto", "Error!!!", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_jButtonSaveActionPerformed

    private void jButtonAddPhoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddPhoneActionPerformed
        addOrModifyPhoneNumbers(true, evt);
    }//GEN-LAST:event_jButtonAddPhoneActionPerformed

    private void jButtonModifyPhoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModifyPhoneActionPerformed
        addOrModifyPhoneNumbers(false, evt);
    }//GEN-LAST:event_jButtonModifyPhoneActionPerformed

    private void jButtonDeletePhoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeletePhoneActionPerformed
        DefaultListModel model = (DefaultListModel) jListPhones.getModel();
        int index = jListPhones.getSelectedIndex();
        
        model.removeElementAt(index);
        
        jListPhones.setModel(model);
    }//GEN-LAST:event_jButtonDeletePhoneActionPerformed

    /**
     * Esta funcion realiza las operaciones para agregar o modificar los numeros
     * telefonicos del contacto
     *
     * @param flag
     * <code>TRUE</code> para agregar,
     * <code>FALSE</code> para modificar
     * @param evt Evento lanzado por el spinner o por el listbox
     */
    private void addOrModifyPhoneNumbers(boolean flag, Object evt) {
        String titulo = "";
        java.awt.event.ActionEvent bEvent = (java.awt.event.ActionEvent) evt;
        javax.swing.JButton but = (javax.swing.JButton) bEvent.getSource();

        if (but.getText().equals("Agregar Telefono")) {
            titulo = "Nuevo Telefono";
        } else {
            titulo = "Corregir numero";
        }

        long telefono;
        try {
            if (!errorNuevoTelefono) {
                String numero = JOptionPane.showInputDialog(parent, "Por favor ingrese el nuevo numero telefonico",
                        titulo, JOptionPane.OK_CANCEL_OPTION);
                if (numero != null) {
                    if (numero.length() > 6 && numero.length() < 11) {
                        telefono = Long.parseLong(numero);
                        DefaultListModel<Long> model = (DefaultListModel<Long>) jListPhones.getModel();
                        if (flag) {
                            model.addElement(telefono);
                        } else {
                            int index = jListPhones.getSelectedIndex();
                            model.setElementAt(telefono, index);
                        }
                        jListPhones.setModel(model);
                    } else {
                        errorNuevoTelefono = true;
                        JOptionPane.showMessageDialog(parent, "Por favor ingrese un numero correcto.\nUn numero telefonico debe tener por lo menos 7 digitos y "
                                + "como mucho 10 digitos", "Numero Erroneo!!!",
                                JOptionPane.WARNING_MESSAGE, new ImageIcon(getClass().getResource("/presentation/view/images/Exclamation.png")));
                    }
                }
            }
        } catch (NumberFormatException e) {
            errorNuevoTelefono = true;
            JOptionPane.showMessageDialog(parent, "Por favor ingrese un numero correcto.",
                    "Numero Erroneo!!!", JOptionPane.WARNING_MESSAGE, new ImageIcon(getClass().getResource("/presentation/view/images/Exclamation.png")));
        } finally {
            errorNuevoTelefono = false;
        }
    }
    private AuxiliarFrame parent;
    private boolean errorNuevoTelefono;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAddPhone;
    private javax.swing.JButton jButtonBack;
    private javax.swing.JButton jButtonDeletePhone;
    private javax.swing.JButton jButtonModifyPhone;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JLabel jLabelEmail;
    private javax.swing.JLabel jLabelLastName;
    private javax.swing.JLabel jLabelNames;
    private javax.swing.JLabel jLabelPhones;
    private javax.swing.JList jListPhones;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextFieldEmail;
    private javax.swing.JTextField jTextFieldLastName;
    private javax.swing.JTextField jTextFieldNames;
    // End of variables declaration//GEN-END:variables
}
